package config

import (
	"io/ioutil"
	"log"

	"gopkg.in/yaml.v3"
)

// DatabaseConfig 数据库连接配置
type DatabaseConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	DBName   string `yaml:"dbname"`
}

// TableMapping 表映射配置
type TableMapping struct {
	SourceTable     string `yaml:"source_table"`
	TargetTable     string `yaml:"target_table"`
	SyncEnabled     bool   `yaml:"sync_enabled"`
	SyncInterval    int    `yaml:"sync_interval"` // 同步间隔(秒)
	IncrementalSync bool   `yaml:"incremental_sync"` // 是否启用增量同步
	PrimaryKeyField string `yaml:"primary_key_field"` // 主键字段名，用于增量同步数据比较
}

// RedisConfig Redis配置
type RedisConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Password string `yaml:"password"`
	DB       int    `yaml:"db"`
}

// SyncConfig 同步任务配置
type SyncConfig struct {
	Source      DatabaseConfig `yaml:"source"`
	Target      DatabaseConfig `yaml:"target"`
	Redis       *RedisConfig   `yaml:"redis,omitempty"` // 可选Redis配置
	TableMappings []TableMapping `yaml:"table_mappings"`
}

// Config 应用配置
type Config struct {
	SyncTasks []SyncConfig `yaml:"sync_tasks"`
}

// LoadConfig 从文件加载配置
func LoadConfig(filePath string) (*Config, error) {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		log.Printf("读取配置文件失败: %v", err)
		return nil, err
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		log.Printf("解析配置文件失败: %v", err)
		return nil, err
	}

	return &config, nil
}